实例详解JavaScript获取多个id | 您所在的位置:网站首页 › JavaScript 运算符 › 实例详解JavaScript获取多个id |
编写一个在javascript中获取多个id的示例代码。 通过在“querySelectorAll”中指定多个“id”。 指定不存在的id不会出错。 获取多个id使用“querySelectorAll”检索多个“id”。 aaa bbb ccc const nodelist = document.querySelectorAll('#one, #two, #three'); for(let item of nodelist){ console.log( item.textContent ) }执行结果 “NodeList”可以作为数组处理,因此也可以使用“forEach”等。 const nodelist = document.querySelectorAll('#one, #two, #three'); nodelist.forEach(v => { console.log(v.textContent); });还可以在数组中准备“id”,然后检索它。 const ids = ['one', 'two', 'three']; const nodelist = document.querySelectorAll( ids.map(id => `#${id}`).join(', ') ); for(let item of nodelist){ console.log( item.textContent ) }指定一个不存在的id指定不存在的“id”不会出错。 const nodelist = document.querySelectorAll('#four, #five'); nodelist.forEach(v => { console.log(v.textContent); // 不出错,不输出任何内容 });本文来源:词雅网 本文地址:https://www.ciyawang.com/javascript-queryselectorall.html 本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。 |
CopyRight 2018-2019 实验室设备网 版权所有 |